package tt.dz.biz.job;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.Assert;
import tt.dz.biz.dao.common.CommonDAO;
import tt.dz.biz.service.Job.JobLockService;
import tt.dz.biz.task.DailyDealTask;
import tt.dz.common.AppContxtUtil;
import tt.dz.common.BusinessException;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.SysState;
import tt.dz.common.DzConstants.bizSysCode;
import tt.dz.common.DzConstants.sysJob;
import tt.dz.common.LogUtil;
import tt.dz.vo.JobLockVO;

public class DailyAccountJob
  extends AbstractJob
{
  protected void executeJob(JobExecutionContext context)
    throws JobExecutionException
  {
    try
    {
      DailyDealTask changeDayTask = new DailyDealTask(DzConstants.sysJob.CHANGE_DAY_TASK.value());
      changeDayTask.executeTask();
      DailyDealTask dailyAccountTask = new DailyDealTask(DzConstants.sysJob.DAILY_ACCOUNT_TASK.value());
      dailyAccountTask.executeTask();
      DailyDealTask calcBalTask = new DailyDealTask(DzConstants.sysJob.CALC_BALANCE_TASK.value());
      calcBalTask.executeTask();
    }
    catch (Exception e)
    {
      LogUtil.error("DailyAccountJob：：执行日终批量处理发生异常", e);
      throw new JobExecutionException(e);
    }
  }
  
  public boolean beforeExecute()
    throws JobExecutionException
  {
    try
    {
      Assert.notNull(this.jobCode, "jobCode参数是必须设置，请检查 getJobCode方法");
      this.jobLockService = ((JobLockService)AppContxtUtil.getBean("jobLockService"));
      Assert.notNull(this.jobLockService, "从容器中获取jobLockService异常，请联系管理员。");
      this.jobvo = this.jobLockService.updateJobStatusForLock(this.jobCode);
      if (null == this.jobvo) {
        return false;
      }
      CommonDAO commonDAO = (CommonDAO)AppContxtUtil.getBean("commonDAO");
      String stateCode = commonDAO.getCurrentSysState(DzConstants.bizSysCode.MAIN_SERVER.value());
      if (!this.jobvo.getStateCode().equals(stateCode)) {
        throw new BusinessException("系统状态为" + stateCode + "与运行日终批处理需要的状态" + DzConstants.SysState.NORMAL_RUNNING.value() + "不一致，不能执行日切任务。");
      }
      Date currentDBTime = commonDAO.getDBCurrentTime();
      if ((this.jobvo.getLastRunTime() != null) && (currentDBTime != null))
      {
        DateFormat sf = new SimpleDateFormat("yyyyMMdd");
        int d1 = Integer.valueOf(sf.format(this.jobvo.getLastRunTime())).intValue();
        int d2 = Integer.valueOf(sf.format(currentDBTime)).intValue();
        if (d2 - d1 < 1) {
          throw new BusinessException("本次执行日切时间（" + d2 + "）与上次执行日切时间(" + d1 + ")间隔小于1天，不能重复执行。");
        }
      }
      return true;
    }
    catch (Exception e)
    {
      LogUtil.error(e.getMessage(), e);
      throw new JobExecutionException(e);
    }
  }
  
  protected String getJobCode()
  {
    return DzConstants.sysJob.DAILY_BATCH_JOB.value();
  }
}
